package com.boruiimage.demo.controller;


import com.boruiimage.demo.doMain.*;
import com.boruiimage.demo.repository.registerDao;
import com.boruiimage.demo.repository.registerMemberUserDao;
import com.boruiimage.demo.utils.*;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.gson.reflect.TypeToken;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/wxpay/precreate")
public class WXPayPrecreateController {
    /**
     * 微信支付-扫码支付.
     * <p>
     * detailed description
     *
     * @author Mengday Zhang
     * @version 1.0
     * @since 2018/6/18
     */
        @Autowired
        private WXPay wxPay;

        @Autowired
        private WXPayClient wxPayClient;
        private registerDao rd;
        /**
         * 扫码支付 - 统一下单
         * 相当于支付不的电脑网站支付
         *
         * <a href="https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1">扫码支付API</a>
         */
        //app端
        @PostMapping("")
        @ResponseBody
        public Result precreate(@RequestBody Map<String,String>map, HttpServletRequest request, HttpServletResponse response) throws Exception {
            Result rs=new Result();
            String ResultImg="";
            Map<String, String> reqData = new HashMap<>();
            reqData.put("out_trade_no", String.valueOf(System.nanoTime()));
            reqData.put("trade_type", "NATIVE");
            // 附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用。
            imageResult re=new imageResult();
             re.setUserName(map.get("userName"));
             re.setProductId(map.get("type"));
             re.setImageName(map.get("imageName"));
             re.setImageresult(map.get("imageresult"));
            String json_string = JsonUtils.serialize(re);
            System.out.println(json_string+"json_string");
                //获得连接池的配置对象
                JedisPoolConfig config=new JedisPoolConfig();
                //设置最大连接数
                config.setMaxTotal(30);
                //设置最大空闲数
                config.setMaxIdle(10);
                //获得连接池
                JedisPool jedisPool=new JedisPool(config, "172.17.0.3", 6379);
                Jedis jedis=null;
                try {
                    //通过连接池获得jedis
                    jedis=jedisPool.getResource();
                    //设置数据
                    jedis.set("attach",json_string);
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }finally{
                    if (jedis!=null) {
                        jedis.close();
                    }
                    if (jedisPool!=null) {
                        jedisPool.close();
                    }
                }

            //Redis.getJedis().expire("attach", 200);
             //reqData.put("attach",json_string);
            reqData.put("prepay_id","1");
            //reqData.put("detail", map.get("type"));
            reqData.put("body", "商户下单");
            // 订单总金额，单位为分
            String servertype=map.get("type");
            if(servertype.equals("1")){//金牌会员
                reqData.put("total_fee", "3");
            }else if(servertype.equals("2")){//银牌会员
                reqData.put("total_fee", "2");
            }
            else if(servertype.equals("3")){//铜牌会员
                reqData.put("total_fee", "1");
            }else if(servertype.equals("5")){//人工服务
                reqData.put("total_fee", "2");
            }
            else if(servertype.equals("4")){//系统服务
                reqData.put("total_fee", "1");
            }
            else if(servertype.equals("6")){//司法鉴定
                reqData.put("total_fee", "1");
            }
            //添加临时信息
            //rd.addmess(map.get("userName"),map.get("type"));
            //reqData.put("total_fee", "1");
            // APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。
            reqData.put("spbill_create_ip", "47.92.98.22");
            // 异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数。
              reqData.put("notify_url", "http://47.92.98.22:8090/wxpay/precreate/notify");
            // 自定义参数, 可以为终端设备号(门店号或收银设备ID)，PC网页或公众号内支付可以传"WEB"
            reqData.put("device_info", "");

            Map<String, String> responseMap = wxPay.unifiedOrder(reqData);
            System.out.println(responseMap.toString());
            String returnCode = responseMap.get("return_code");
            String resultCode = responseMap.get("result_code");
            if (WXPayConstants.SUCCESS.equals(returnCode) && WXPayConstants.SUCCESS.equals(resultCode)) {
                String prepayId = responseMap.get("prepay_id");
                String codeUrl = responseMap.get("code_url");
                BufferedImage image = payUtil.getQRCodeImge(codeUrl);
                response.setContentType("image/jpeg");
                response.setHeader("Pragma","no-cache");
                response.setHeader("Cache-Control","no-cache");
                response.setIntHeader("Expires",-1);
                //ImageIO.write(image, "png", response.getOutputStream());
                //ResultImg=new String("data:image/png;base64,"+ Base64.encode(image.toString()));
                rs.setMsg(prepayId);
                rs.setImgName(ResultImg);
                System.out.println(rs);
            }
          return rs;
        }

          @Autowired
          registerMemberUserDao rmudd;
          @Autowired
          registerDao rds;
        //网页端
        @PostMapping("/interNet")
        @ResponseBody
        public void precreate(@RequestParam(value = "userName")String userName,@RequestParam(value = "type")String type,@RequestParam(value = "imageNames")String imageName,@RequestParam(value = "imageresult")String imageresult, HttpServletRequest request, HttpServletResponse response) throws Exception {
             Result rs=new Result();
            String ResultImg="";
            Map<String, String> reqData = new HashMap<>();
            reqData.put("out_trade_no", String.valueOf(System.nanoTime()));
            reqData.put("trade_type", "NATIVE");
            Random randoms =new Random();
            int prepay_id=randoms.nextInt(10000);
            reqData.put("prepay_id", String.valueOf(prepay_id));
            System.out.println(String.valueOf(prepay_id)+"=====prepay_id");
            // 附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用。
            imageResult re=new imageResult();
            re.setUserName(AES.encrypt(userName));
            re.setProductId(type);
            re.setImageName(imageName);
            re.setImageresult(imageresult);
            re.setGoodsId(String.valueOf(prepay_id));
            String json_string = JsonUtils.serialize(re);
            System.out.println(json_string);
            rmudd.addGoods(String.valueOf(prepay_id),"0",null);
            //reqData.put("attach",json_string);
            //放入readis里面
            //获得连接池的配置对象
            JedisPoolConfig config=new JedisPoolConfig();
            //设置最大连接数
            config.setMaxTotal(30);
            //设置最大空闲数
            config.setMaxIdle(10);
            //获得连接池
            JedisPool jedisPool=new JedisPool(config, "172.17.0.3", 6379);
            Jedis jedis=null;
            try {
                //通过连接池获得jedis
                jedis=jedisPool.getResource();
                //设置数据
                jedis.set("attach",json_string);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }finally{
                if (jedis!=null) {
                    jedis.close();
                }
                if (jedisPool!=null) {
                    jedisPool.close();
                }
            }

            //reqData.put("detail", map.get("type"));
            reqData.put("body", "商户下单");
            // 订单总金额，单位为分
            String servertype=type;
            if(servertype.equals("1")){//金牌会员
                reqData.put("total_fee", "3");
            }else if(servertype.equals("2")){//银牌会员
                reqData.put("total_fee", "2");
            }
            else if(servertype.equals("3")){//铜牌会员
                reqData.put("total_fee", "1");
            }else if(servertype.equals("5")){//人工服务
                reqData.put("total_fee", "2");
            }
            else if(servertype.equals("4")){//系统服务
                reqData.put("total_fee", "1");
            }
            else if(servertype.equals("6")){//司法鉴定
                reqData.put("total_fee", "1");
            }
            //添加临时信息
            //rd.addmess(map.get("userName"),map.get("type"));
            //reqData.put("total_fee", "1");
            // APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP。
            reqData.put("spbill_create_ip", "47.92.98.22");
            // 异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数。
            reqData.put("notify_url", "http://47.92.98.22:8090/wxpay/precreate/notify");
            // 自定义参数, 可以为终端设备号(门店号或收银设备ID)，PC网页或公众号内支付可以传"WEB"
            reqData.put("device_info", "");

            Map<String, String> responseMap = wxPay.unifiedOrder(reqData);
            System.out.println(responseMap.toString());
            String returnCode = responseMap.get("return_code");
            String resultCode = responseMap.get("result_code");
            if (WXPayConstants.SUCCESS.equals(returnCode) && WXPayConstants.SUCCESS.equals(resultCode)) {
                String prepayId = responseMap.get("prepay_id");
                String codeUrl = responseMap.get("code_url");
                BufferedImage image = payUtil.getQRCodeImge(codeUrl);
                response.setContentType("image/jpeg");
                response.setHeader("Pragma","no-cache");
                response.setHeader("Cache-Control","no-cache");
                response.setIntHeader("Expires",-1);
                Random random=new Random();
                int i=random.nextInt(1000);
                OutputStream ops = new FileOutputStream(new File("/opt/bigdata_px_api/images/"+i+".png"));
                ImageIO.write(image, "png",ops);
                ResultImg="http://52borui.cn:8081/"+i+".png";
                //是为了获取服务器中的二维码
                if(servertype.equals("4")){
                    rds.addmess("system",ResultImg,null);
                } else if(servertype.equals("1")){
                    rds.addmess("jin",ResultImg,null);
                }else if(servertype.equals("2")){
                    rds.addmess("yin",ResultImg,null);
                }else if(servertype.equals("3")){
                    rds.addmess("tong",ResultImg,null);
                }
                else if(servertype.equals("5")){
                    rds.addmess("person",ResultImg,null);
                }
            }
        }
             @Autowired
             registerDao rdes;
             @RequestMapping("/imgUrl")
             @ResponseBody
             public Result show(@RequestParam(value = "connect")String connect){
                Result rs=new Result();
                 String code=rdes.Select(connect);

                 JedisPoolConfig config=new JedisPoolConfig();
                 //设置最大连接数
                 config.setMaxTotal(30);
                 //设置最大空闲数
                 config.setMaxIdle(10);
                 //获得连接池
                 JedisPool jedisPool=new JedisPool(config, "172.17.0.3", 6379);
                 Jedis jedis=null;
                 try {
                     //通过连接池获得jedis
                     jedis=jedisPool.getResource();
                     imageResult result12 = JsonUtils.deserialize(jedis.get("attach"), new TypeToken<imageResult>(){}.getType());
                     System.out.println(result12+"result12");
                     String goodsId=result12.getGoodsId();
                     rs.setImgName(code);
                     rs.setMsg(goodsId);
                 } catch (Exception e) {
                     // TODO: handle exception
                     e.printStackTrace();
                 }finally{
                     if (jedis!=null) {
                         jedis.close();
                     }
                     if (jedisPool!=null) {
                         jedisPool.close();
                     }
                 }
                 //rdes.delByconnect(connect);
                 System.out.println(code+"tupian");
                 System.out.println(rs.getImgName()+"tupian");
                 return rs;
             }
        /**
         *
         * @param request
         * @return
         * @throws Exception
         */
        @Autowired
        registerMemberUserDao rmud;
        @RequestMapping("/notify")
        public void precreateNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
            Result rse=new Result();
          try{
              Map<String, String> reqData = wxPayClient.getNotifyParameter(request);
              String goodsId=null;

              if(reqData.get("return_code").equals("SUCCESS")){

                  String username=null;
                  String productId=null;
                  String imgName=null;
                  String imageResult=null;

                  //获得连接池的配置对象
                  JedisPoolConfig config=new JedisPoolConfig();

                  //设置最大连接数
                  config.setMaxTotal(30);

                  //设置最大空闲数
                  config.setMaxIdle(10);

                  //获得连接池
                  JedisPool jedisPool=new JedisPool(config, "172.17.0.3", 6379);

                  Jedis jedis=null;
                  try {
                      //通过连接池获得jedis
                      jedis=jedisPool.getResource();

                      imageResult result12 = JsonUtils.deserialize(jedis.get("attach"), new TypeToken<imageResult>(){}.getType());

                      System.out.println(result12+"result12");

                      username=result12.getUserName();
                      productId=result12.getProductId();
                      imgName=result12.getImageName();
                      imageResult=result12.getImageresult();
                      goodsId=result12.getGoodsId();
                      jedis.del("attach");

                  } catch (Exception e) {
                      // TODO: handle exception
                      e.printStackTrace();
                  }finally{
                      if (jedis!=null) {
                          jedis.close();
                      }
                      if (jedisPool!=null) {
                          jedisPool.close();
                      }
                  }
                  //修改 该商品id的结果
                  rmud.upGoods("SUCCESS",goodsId);

                  //首先查询该用户是否是会员
                  //memberuser us = rmud.us(username);
                  member mbmberInfo;
                  //123 是开通会员
                  if(productId.equals("1")||productId.equals("2")||productId.equals("3")){
                      try{
                          //添加会员
                          //首先vipcode查询人工使用次数和系统使用次数
                          member mb=rmud.mb(Integer.parseInt(productId));
                          //添加会员信息
                          Result rs=rmud.addMemberUser(username,mb.getSystemNum(),mb.getPersonNum(),null,Integer.parseInt(productId));
                          mbmberInfo =rmud.moneyByVipCode(Integer.parseInt(productId));
                          //添加充值记录
                          Result res=rmud.addRechargeInfo(username,mbmberInfo.getVipType(), Double.valueOf((reqData.get("total_fee"))),"微信",null);
                      }catch (Exception e){
                          throw e;
                      }
                  }else if(productId.equals("4")){//非会员code
                      //通过产品ID获取产品服务类型
                      serverInfo so=rmud.selectServerInfo(Integer.parseInt(productId));
                      Integer money=rmud.moneyByServerCode(Integer.parseInt(productId));
                      Result res=rmud.addRechargeInfo(username,so.getServerType(), Double.valueOf((reqData.get("total_fee"))),"微信",null);
                      rmud.addImg(username,imgName,"http://52borui.cn:8081/" +imgName,imageResult,so.getServerType(),money,"微信");
                  }else if(productId.equals("5")){
                      //通过产品ID获取产品服务类型
                      serverInfo so=rmud.selectServerInfo(Integer.parseInt(productId));
                      Integer money=rmud.moneyByServerCode(Integer.parseInt(productId));
                      Result res=rmud.addRechargeInfo(username,so.getServerType(), Double.valueOf((reqData.get("total_fee"))),"微信",null);
                      rmud.addImg(username,imgName,"http://52borui.cn:8081/" +imgName,"正在鉴定",so.getServerType(),money,"微信");
                  }else if(productId.equals("6")){
                      //通过产品ID获取产品服务类型
                      serverInfo so=rmud.selectServerInfo(Integer.parseInt(productId));
                      Integer money=rmud.moneyByServerCode(Integer.parseInt(productId));
                      Result res=rmud.addRechargeInfo(username,so.getServerType(), Double.valueOf((reqData.get("total_fee"))),"微信",null);

                      if(rmud.SelectimgInfo(username,imgName)!=null){//修改图片记录
                           rmud.updateImgInfo("http://52borui.cn:8081/" +imgName,imageResult,money,"微信",username,imgName);
                      }else {//添加图片记录
                          rmud.addImg(username,imgName,"http://52borui.cn:8081/" +imgName,imageResult,so.getServerType(),money,"微信");
                      }

                  }else if(productId==null){
                      return;
                  }
              }else {
                  rmud.upGoods("UNSUCCESS",goodsId);
              }

           /*   // 特别提醒：商户系统对于支付结果通知的内容一定要做签名验证,并校验返回的订单金额是否与商户侧的订单金额一致，防止数据泄漏导致出现“假通知”，造成资金损失。
              boolean signatureValid = wxPay.isPayResultNotifySignatureValid(reqData);
              if (signatureValid) {
                  *//**
                   * 注意：同样的通知可能会多次发送给商户系统。商户系统必须能够正确处理重复的通知。
                   * 推荐的做法是，当收到通知进行处理时，首先检查对应业务数据的状态，
                   * 判断该通知是否已经处理过，如果没有处理过再进行处理，如果处理过直接返回结果成功。
                   * 在对业务数据进行状态检查和处理之前，要采用数据锁进行并发控制，以避免函数重入造成的数据混乱。
                   *//*
                  Map<String, String> responseMap = new HashMap<>(2);
                  responseMap.put("return_code", "SUCCESS");
                  responseMap.put("return_msg", "OK");
                  String responseXml = WXPayUtil.mapToXml(responseMap);
                  response.setContentType("text/xml");
                  response.getWriter().write(responseXml);
                  response.flushBuffer();*/
              /*}*/
          }catch (Exception e){
              throw e;
          }
        }
       @Autowired
       registerMemberUserDao rmudss;
        @RequestMapping("/showresult")
        @ResponseBody
      public Result showRe(HttpServletRequest request,@RequestParam(value = "result")String goodsId){
            System.out.println(goodsId);
            Result rs=new Result();
            rs.setMsg(rmudss.selectResult(goodsId));
          return rs;
      }

}

